package cc.ufinity.networkdiagnose.widget;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import cc.ufinity.networkdiagnose.manager.DBManager;
import cc.ufinity.networkdiagnose.manager.FTPConfig;
import cc.ufinity.networkdiagnose.manager.FtpTestManager;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.TelManager;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.manager.Task.GPS;
import cc.ufinity.networkdiagnose.manager.Task.GSM;
import cc.ufinity.networkdiagnose.manager.Task.TD;
import cc.ufinity.networkdiagnose.util.GPSUtils;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.view.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.net.ConnectivityManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.ScrollView;
import android.widget.Toast;

public class GeneralTestWidget extends FrameLayout {

    protected final static int TASK_PERFORM_INTERVAL = 10000;
    protected static final String TAG_REFER_TASK = "task";
    protected static final int TOAST_MSG_DISPLAY_TIME = 15000;// 定义消息显示时间，默认8秒

    protected boolean executable = true;

    protected ProgressDialog progressDialog;
    protected ProgressDialog messageDialog;
    protected AlertDialog wifiListDialog;

    protected ScanResult selectedScanResult;

    public GeneralTestWidget(Activity context) {
        super(context);
        if (this instanceof TaskWidget) {
            context.getIntent().putExtra(MessageWhat.INDEX_FLAG_NAME, MessageWhat.INDEX_FLAG_VALUE);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_FLAG_NAME, 0);
        }
    }

    protected FTPConfig getFTPConfig(Activity ctx) {
        DBManager db = new DBManager(ctx);
        final FTPConfig ftp = db.getFtp();
        db.release();
        if (ftp == null) {
            showMessage(ctx, "获取FTP账号失败，请检查FTP配置是否正确.");
            return null;
        } else {
            return ftp;
        }
    }

    public void sendMsg(int what, Handler handler) {
        if (null != handler) {
            Message msg = handler.obtainMessage();
            msg.what = what;
            msg.sendToTarget();
        }
    }

    protected void showWifiListDialog(Activity ctx, WlanManager wlanManager, final Handler handler) {
        final List<ScanResult> scanResults = wlanManager.getScanResults();
        String[] apList = createWifiTitles(scanResults);
        AlertDialog.Builder ad = new AlertDialog.Builder(ctx);
        ad.setTitle("Wifi列表");
        ad.setSingleChoiceItems(apList, 0, new android.content.DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                selectedScanResult = scanResults.get(which);
                Message msg = new Message();
                msg.what = MessageWhat.WIFI_SELECTED;
                handler.sendMessage(msg);
                wifiListDialog.dismiss();
            }
        });
        wifiListDialog = ad.create();
        wifiListDialog.show();
    }
    protected void showMessageDialog(Activity ctx, final String text) {
        messageDialog = new ProgressDialog(ctx);
        messageDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        messageDialog.setTitle("请稍等");
        messageDialog.setIcon(R.drawable.smile);
        messageDialog.setMessage(text);
        messageDialog.show();
    }
 
    protected void dismissMessageDialog() {
        if (messageDialog != null) {
            messageDialog.dismiss();
        }
    }

    protected void showProgressDialog(Activity ctx, final String text, final int max) {
        progressDialog = new ProgressDialog(ctx);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setTitle("请稍等");
        progressDialog.setIcon(R.drawable.smile);
        progressDialog.setMessage(text);
        progressDialog.setProgress(0);
        progressDialog.setIndeterminate(false);
        progressDialog.setMax(max);
        progressDialog.setCancelable(true);
        progressDialog.setOnCancelListener(new OnCancelListener() {
            public void onCancel(DialogInterface dialog) {
                executable = false;
                dialog.cancel();
            }
        });
        progressDialog.show();
    }

    protected void setDialogProgress(int value) {
        if (progressDialog != null)
            progressDialog.setProgress(value);
    }

    protected void dismissProgressDialog() {
        if (progressDialog != null)
            progressDialog.dismiss();
    }

    protected void showMessage(Context ctx, String msg) {
        Toast.makeText(ctx, msg, Toast.LENGTH_LONG).show();
    }

    protected void back(Activity context) {
        TestWidget tw = new TestWidget(context);
        context.setContentView(tw);
    }

    protected void backToConfig(Activity context) {
        SettingWidget tw = new SettingWidget(context);
        context.setContentView(tw);
    }

    protected void backToTask(Activity context) {
        TaskWidget tw = new TaskWidget(context);
        context.setContentView(tw);
        tw.start();
    }

    protected void setScrollViewDown(final ScrollView svResult) {
        svResult.post(new Runnable() {
            public void run() {
                svResult.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });
    }

    private String[] createWifiTitles(final List<ScanResult> scanResults) {
        String[] l = new String[scanResults.size()];
        int length = scanResults.size();
        for (int i = 0; i < length; i++) {
            ScanResult obj = scanResults.get(i);
            StringBuffer sb = new StringBuffer();
            sb.append('[').append(obj.level).append(']');
            sb.append(obj.SSID).append('\n');
            sb.append(obj.BSSID);
            l[i] = sb.toString();
        }
        return l;
    }
   
    protected boolean uplod(final String fileName, Activity ctx, Handler handler) {
        Message msg = null;
        boolean success = false;
        DBManager db = new DBManager(ctx);
        FTPConfig ftp = db.getFtp();
        db.release();
        if (ftp == null) {
            msg = handler.obtainMessage();
            msg.what = MessageWhat.FTP_ACCOUNT_INVALID;
            msg.sendToTarget();
            return success;
        }
        String localPath = Environment.getExternalStorageDirectory() + "/";
        String remotePath = "/";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        Date curDate = new Date(System.currentTimeMillis());
        remotePath = remotePath + formatter.format(curDate) + "/";
        FtpTestManager fm = new FtpTestManager(localPath, remotePath, fileName);

        if (fm.login(ftp.address, ftp.port, ftp.userName, ftp.password)) {
            if (fm.upload() > -1) {
                msg = handler.obtainMessage();
                msg.what = MessageWhat.FTP_UPLOAD_TASK_DONE;
                msg.sendToTarget();
                fm.logout();
                File file = new File(localPath + fileName);
                if (file.exists()) {
                    file.delete();
                }
                success = true;
            } else {
                msg = handler.obtainMessage();
                msg.what = MessageWhat.FTP_UPLOAD_FAILED;
                msg.sendToTarget();
            }
        } else {
            msg = handler.obtainMessage();
            msg.what = MessageWhat.FTP_LOGIN_FAILED;
            msg.sendToTarget();
        }
        return success;
    }

    protected void initTask(final Task task, Activity ctx, int type) {
        if (type == ConnectivityManager.TYPE_WIFI) {
            task.netType = "WLAN测试";
            WlanManager wmanager = new WlanManager(ctx);
            WifiInfo info = wmanager.getCurrentNetwork();
            task.mac = info.getMacAddress();
            task.rssi = String.valueOf(info.getRssi());

        } else {
            task.netType = "GSM测试";
        }

        TelManager tm = new TelManager(ctx);
        task.testPhone = tm.getPhoneNumber();
        GPSUtils gpsUtil = new GPSUtils(ctx);
        double longitude = gpsUtil.getLongitude();
        double latitude = gpsUtil.getLatitude();

        Log.d("GPS", "longitude:" + longitude + ";latitude" + latitude);
        // if (longitude != 0 && latitude != 0) {
        GPS gps = task.newGPS();
        gps.Longitute = Double.toString(longitude);
        gps.Latitute = Double.toString(latitude);
        task.gps = gps;

        int lac = tm.getLac();
        int ci = tm.getCI();
        Log.d("Tel", "lac:" + lac + ";ci" + ci);
        task.lac = String.valueOf(lac);
        task.ci = String.valueOf(ci);

        GSM gsm = task.newGSM();
        gsm.netType = tm.getNetworkType();
        gsm.ber = String.valueOf(tm.getBER());
        gsm.ci = String.valueOf(tm.getCI());
        gsm.lac = String.valueOf(tm.getLac());
        gsm.fieldstrength = String.valueOf(tm.getSignalStrength());
        gsm.rssi = "-1";
        task.gsm = gsm;

        TD td = task.newTD();
        td.netType = tm.getNetworkType();
        td.ber = String.valueOf(tm.getBER());
        td.ci = String.valueOf(tm.getCI());
        td.lac = String.valueOf(tm.getLac());
        td.fieldstrength = String.valueOf(tm.getSignalStrength());
        td.rssi = "-1";
        task.td = td;
    }
}
